﻿using MediatR;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using Yitter.IdGenerator;
using Yuekao.API.Write.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Write.CommandHander
{
    public class InstanceAddCommandHandler : IRequestHandler<InstanceAddCommand, APIResult<string>>
    {
        private readonly IBaseRepository<WorkflowInstanceModel> _instancebaseRepository;
        private readonly IWorkflowHost _workflowHost;
        public InstanceAddCommandHandler(IBaseRepository<WorkflowInstanceModel> instancebaseRepository, IWorkflowHost workflowHost)
        {
            _instancebaseRepository = instancebaseRepository;
            _workflowHost = workflowHost;
        }
        public async Task<APIResult<string>> Handle(InstanceAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result=new APIResult<string>();

            var workflowId =await _workflowHost.StartWorkflow(request.DefinitionId,request.Version);

            WorkflowInstanceModel model=new WorkflowInstanceModel();
            model.Id=YitIdHelper.NextId();
            model.WorkflowId = workflowId;
            model.DefinitionId = request.DefinitionId;
            model.Version = request.Version;
            model.Title = request.Title;
            model.StepId = "";
            model.StepName = "";
            model.FormData = request.FormData;
            model.AuditId = 0;
            model.AuditName = "";
            model.CreateName = request.CreateName;
            model.State = "发起";

            _instancebaseRepository.Add(model);

            result.Code=APIEnum.Success;
            result.Message = "流程发起成功";
            result.Data = workflowId;
            return await Task.FromResult(result); 
        }
    }
}
